<template>
  <div>
    <dl>
      <template v-for="userInfo of state.userList" :key="userInfo.id">
        <dt v-if="userInfo.username === state.username">
          {{ userInfo.username }}
        </dt>
        <dt v-else @click="($event) => selectUser(userInfo)">
          <b>{{ userInfo.username }}</b>
        </dt>
      </template>
      <ul>
        <li v-for="(data,index) of messageList" :key="index">
            <p>{{data.fromUsername}}-{{new Date(data.dateTime)}}</p>
            <p>{{data.msg}}</p>
        </li>
      </ul>
      <!-- <dt v-for="userInfo of state.userList" :key="userInfo.id">{{userInfo.username}}</dt> -->
    </dl>
    <h2>{{ state.targetUser.username }}</h2>
    <input type="text" placeholder="" v-model="state.msgText" />
    <button @click="sendMessage">发送</button>
  </div>
</template>

<script setup>
import { io } from "socket.io-client";
import { useRouter } from "vue-router";
import { reactive,computed } from "vue";

const router = useRouter();
console.log(router);
const state = reactive({
  username: router.currentRoute.value.query.username,
  userList: [],
  targetUser: {},
  msgText: "",
  messageBox: {},

});

const messageList = computed (()=>{
   return (state.messageBox[state.username] && state.targetUser) ?
    state.messageBox[state.username].filter(item=>{
        return item.fromUsername == state.targetUser.username || 
               item.toUsername == state.targetUser.username
    }):[]
})

const selectUser = (userInfo) => {
  console.log(userInfo);
  state.targetUser = userInfo;
};
const socket = io("http://localhost:3000", {
  query: {
    username: state.username,
  },
});

const sendMessage = () => {
  if (!state.msgText.length) {
    return 0;
  }
  !state.messageBox[state.username] && (state.messageBox[state.username] = []);
  state.messageBox[state.username].push({
    fromUsername: state.username,
    toUsername: state.targetUser.username,
    msg: state.msgText,
    dateTime: new Date().getTime(),
  });

  socket.emit("send", {
    fromUsername: state.username,
    targetId: state.targetUser.id,
    msg: state.msgText,
  });
  state.msgText=""
};
// 当前在线的人员信息
socket.on("online", (data) => {
  console.log("data", data);
  state.userList = data.userList;
});
socket.on("error", (err) => {
  console.log("网络连接失败请稍后再试");
});
socket.on("receive", (data) => {
  console.log("ssss", data);
  appendMesage(data);

});
function appendMesage(data){
  !state.messageBox[state.username] && (state.messageBox[state.username] = [])
   state.messageBox[state.username].push(data);


}
</script>

<style lang="css" scoped></style>
